﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using SoGame.Model;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using System.Configuration;
using System.Drawing;
using System.Drawing.Imaging;

namespace SoGame.WebServices
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "SoGame" in both code and config file together.
    public class SoGame : ISoGame
    {
        private SoGameDbContext soGameDbContext = new SoGameDbContext();
        private GamePlay gamePlay;

        /// <summary>
        /// Saves the game play.
        /// </summary>
        /// <param name="game">The game.</param>
        /// <param name="score">The score.</param>
        /// <param name="urlPhoto">The URL photo.</param>
        public void SaveGamePlay(string game, int score, string urlPhoto)
        {
            var gamePlay = new GamePlay() { Game = game, Score = score };

#if (ASYNC)
            gamePlay.Photo = GetPhotoBytes(urlPhoto).Result;
            this.soGameDbContext.SaveGamePlay(gamePlay);
#else
            this.gamePlay = gamePlay;
            GetPhotosAsync(urlPhoto);
#endif
        }

        /// <summary>
        /// Saves the game play.
        /// </summary>
        /// <param name="game">The game.</param>
        /// <param name="score">The score.</param>
        /// <param name="photoPath">The photo path.</param>
        public void SaveGamePlayFromNetwork(string game, int score, string photoPath) 
        {    
            var gamePlay = new GamePlay() { Game = game, Score = score };
            if (photoPath != null && photoPath != string.Empty)
            {
                string fullPath = Path.Combine(ConfigurationManager.AppSettings["PhotoPath"], photoPath);
                if (File.Exists(fullPath))
                    using (var ms = new MemoryStream(File.ReadAllBytes(fullPath)))
                    {
                        using (var bitmap = Bitmap.FromStream(ms))
                        {
                            bitmap.RotateFlip(RotateFlipType.RotateNoneFlipX);
                            using (var ms2 = new MemoryStream())
                            {
                                bitmap.Save(ms2, ImageFormat.Jpeg);
                                gamePlay.Photo = ms2.ToArray();
                            }
                        }
                    }
            }
            this.soGameDbContext.SaveGamePlay(gamePlay);
        }

#if(ASYNC)
        /// <summary>
        /// Gets the photo bytes.
        /// </summary>
        /// <param name="urlPhoto">The URL photo.</param>
        /// <returns></returns>
        public async Task<byte[]> GetPhotoBytes(string urlPhoto) {
            byte[] bytes;
            using (var client = new WebClient())
            {
                bytes = await client.DownloadDataTaskAsync(new Uri(urlPhoto, UriKind.RelativeOrAbsolute));
            }

            return bytes;
        } 
#else
        /// <summary>
        /// Gets the photos async.
        /// </summary>
        /// <param name="urlPhoto">The URL photo.</param>
        public void GetPhotosAsync(string urlPhoto) {
            using (var client = new WebClient()) {
                client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(client_DownloadDataCompleted);
                client.DownloadDataAsync(new Uri(urlPhoto, UriKind.RelativeOrAbsolute));
            }
        }

        /// <summary>
        /// Handles the DownloadDataCompleted event of the client control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Net.DownloadDataCompletedEventArgs"/> instance containing the event data.</param>
        void client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
        {
            this.gamePlay.Photo = e.Result;
            this.soGameDbContext.SaveGamePlay(this.gamePlay);
        }
#endif
    }
}
